package com.ruoyi.web.controller.system.api.app;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.interceptor.Authentication;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.service.IPlanDetailsService;
import com.ruoyi.system.api.service.IStFeedbackService;
import com.ruoyi.system.api.service.IStInfoUpdateService;
import com.ruoyi.system.api.service.IUserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PlanAndCaseController
 * @Description: 工作计划与升级Case管理
 * @Author wlf
 * @Date 2020/3/3
 * @Version V1.0
 **/
@Api(tags="工作计划与升级Case管理")
@Controller
@RequestMapping("/api/cc/planAndCase")
public class PlanAndCaseController extends BaseController {

    @Autowired
    IStInfoUpdateService stInfoUpdateService;

    @Autowired
    IPlanDetailsService planDetailsService;

    @Autowired
    IStFeedbackService feedbackService;

    @Autowired
    IUserService userService;

    private static final Logger log = LoggerFactory.getLogger(PlanAndCaseController.class);
    /**
     * 升级Case管理
     * @methodName: caseList
     * @description: TODO
     * @param infoUpdate
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/2 11:09
     **/
    @PostMapping(value = "/caseList")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "升级Case管理接口", httpMethod = "POST", notes = "升级Case管理接口")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "工程师ID", name = "enginnerId", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "服务通知号", name = "serviceNo", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "客户名称", name = "customerName", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "申请时间", name = "createTime", dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> caseList(@RequestBody Map<String, Object> infoUpdate){
        try {
            List<StInfoUpdate> list = stInfoUpdateService.selectUpdateCase(infoUpdate);
            return new ResponseWithData().success(list).msg("success").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 工作计划
     * @methodName: workPlan
     * @description: TODO
     * @param param
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/2 11:09
     **/
    @PostMapping(value = "/workPlan", produces = "application/json")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "工程师ID", name = "enginnerId", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "查询类型", name = "type", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "开始时间", name = "startTime", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "结束时间", name = "endTime", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "默认显示条数（不传则显示所有）", name = "limitNum", dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> workPlan(@RequestBody Map<String, String> param){
        try {
            if (param.get("type") != null) {
                String type = param.get("type");
                String startTime = "";
                String endTime = "";
                Calendar cal = Calendar.getInstance();
                if (type.equals("1") || type.equals("")) {//当前周
                    cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
                    int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
                    if(dayWeek==1){
                        dayWeek = 8;
                    }
                    cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
                    startTime = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
                    System.out.println("所在周星期一的日期：" + startTime);
                    cal.add(Calendar.DATE, 4 +cal.getFirstDayOfWeek());
                    endTime = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
                    System.out.println("所在周星期日的日期：" + endTime);
                    param.put("startTime", startTime + " 00:00:00");
                    param.put("endTime", endTime + " 23:59:59");
                } else if (type.equals("2")) {//当前月
                    // 获取前月的第一天
                    cal.add(Calendar.MONTH, 0);
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    startTime = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
                    // 获取前月的最后一天
                    cal = Calendar.getInstance();
                    cal.add(Calendar.MONTH, 1);
                    cal.set(Calendar.DAY_OF_MONTH, 0);
                    endTime = DateUtils.parseDateToStr("yyyy-MM-dd", cal.getTime());
                    param.put("startTime", startTime + " 00:00:00");
                    param.put("endTime", endTime + " 23:59:59");
                }
            }
            return planDetailsService.selectFseWorkPlan(param);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 查询服务详情(通过服务单号、工程师获取服务及计划详情)
     * @methodName: noticeAndPlanDetails
     * @description: TODO
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/4/20 18:54
     **/
    @PostMapping("/noticeAndPlanDetails")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "查询服务详情", httpMethod = "POST", notes = "查询服务详情")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "服务单号", name = "serviceNo", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "工程师id", name = "enginnerId", required = true, dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> getDetailsByServiceNo(@RequestBody Map<String, Object> params){
        try {
            List<Map<String, Object>> list = stInfoUpdateService.noticeAndPlanDetails(params);
            return new ResponseWithData<>().success(list).msg("查询成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 工作计划——任务列表
     * @methodName: workPlay
     * @description: TODO
     * @param planDetails
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/9 11:09
     **/
    @PostMapping(value = "/planList", produces = "application/json")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "工作计划——任务列表接口", httpMethod = "POST", notes = "工作计划——任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "工程师FSE的主键ID", name = "enginnerId", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "服务单子表主键ID（可能有多个用逗号分隔）", name = "planIds", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> planList(@RequestBody Map<String, Object> params){
        try {
            List<PlanDetails> list = planDetailsService.selectWorkPlanList(params);
            return new ResponseWithData<>().success(list).msg("查询成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 工作计划——修改工作计划
     * @methodName: workPlay
     * @description: TODO
     * @param planDetails
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/9 11:09
     **/
    @PostMapping("/updatePlan")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "修改工作计划", httpMethod = "POST", notes = "修改工作计划")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "预计上门时间", name = "estimatedVisitingTime", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "预计工时", name = "estimatedWorkingHours", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "预计结束时间", name = "estimatedDepartureTime", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "服务单子表主键ID（可能有多个用逗号分隔）", name = "planIds", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "自动签离时间", name = "signOffAutoHour", required = true, dataType = "Double", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> updatePlan(@RequestBody Map<String, String> planDetails){
        try {
            planDetailsService.updatePlanWidthIds(planDetails);
            return new ResponseWithData<>().success(planDetails).msg("保存询成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 问题反馈
     * @methodName: workPlay
     * @description: TODO
     * @param stFeedback
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/9 11:09
     **/
    @PostMapping("/feedback")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "问题反馈", httpMethod = "POST", notes = "问题反馈")
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功")
    })
    public ResponseWithData<?> feedback(@RequestBody StFeedback stFeedback){
        try {
            feedbackService.insertStFeedback(stFeedback);
            return new ResponseWithData<>().success(stFeedback).msg("保存成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

    /**
     * 休假
     * @methodName: getErrorFse
     * @description: TODO
     * @return: com.ruoyi.system.api.ResponseWithData<?>
     * @author: wlf
     * @date: 2020/3/9 11:09
     **/
    @PostMapping ("/getErrorFse")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "休假", httpMethod = "POST", notes = "休假")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户id", name = "id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(value = "休假状态", name = "workday", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" )
    })
    public ResponseWithData<?> takeVacation(@RequestParam Long id, @RequestParam String workday){
        try {
            User user = new User();
            user.setId(id);
            user.setWorkday(workday);
            userService.updateUser(user);
            return new ResponseWithData().success().msg("保存成功").code(200);
        }catch (Exception e){
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }


    /**
     *  CC调用 Case关闭
     *
     * @param requestId	信息修改申请ID
     * @param closePersonId	关闭服务通知人员ID
     * @return com.ruoyi.system.api.ResponseWithData
     * @author yzg
     * @date 2020/4/5 12:07 下午
     */
    @GetMapping("/handleCase")
    @ResponseBody
    @Authentication(tokenRequired = true, signRequired = true)
    @ApiOperation(value = "CC调用 Case关闭", httpMethod = "GET", notes = "CC调用 Case关闭")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "信息修改申请ID", name = "requestId", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "关闭服务通知人员ID", name = "closePersonId", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "code 为 500 系统异常"),
            @ApiResponse(code = 200, message = "code 为 200 成功" )
    })
    public ResponseWithData handleCase(@RequestParam("requestId") String requestId, @RequestParam("closePersonId") String closePersonId) {
        try {
            return stInfoUpdateService.handleCase(requestId, closePersonId);
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            return new ResponseWithData().error().msg("系统异常").code(500);
        }
    }

}
